package com.lej.theme.toast

import android.content.Context
import android.view.LayoutInflater
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.appcompat.widget.AppCompatImageView
import com.lej.theme.R
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 *  author: cjq
 *  date  : 2022/7/5 0005
 *  desc  :
 */
object CustomTips {
    private var mDialog: QMUITipDialog? = null

    fun Context.showTips(
        tipsStr: CharSequence? = "",
        closeTime: Long = 2000L,
        isFail: Boolean = false
    ) {
        if (tipsStr == null) return
        mDialog?.dismiss()
        mDialog = createDialog(this, tipsStr, isFail)
        mDialog?.show()
        GlobalScope.launch {
            delay(closeTime)
            mDialog?.dismiss()
        }
    }

    fun Context.showTips(@StringRes tipsStr: Int, closeTime: Long = 2000L, isFail: Boolean = false) {
        showTips(resources.getString(tipsStr), closeTime, isFail)
    }

    private fun createDialog(
        context: Context,
        tipsStr: CharSequence,
        isFail: Boolean
    ): QMUITipDialog {
        val dialog = QMUITipDialog(context)
        val view = LayoutInflater.from(context).inflate(R.layout.theme_custom_toast, null, true)
        view.findViewById<TextView>(R.id.tv_content).text = tipsStr
        view.findViewById<AppCompatImageView>(R.id.iv_icon)
            .setImageResource(if (isFail) R.drawable.ic_custom_toast_fail else R.drawable.ic_custom_toast_success)
        dialog.setContentView(view)
        return dialog
    }
}